#!/usr/bin/python

# Modify jscoverage.js to use window.parent instead of window.opener.
js = open('build/instrumented/jscoverage.js').read()
start = js.index('function jscoverage_init(w)')
end = js.index('var jscoverage_currentFile = null;', start)
js = js[:start] + '''
function jscoverage_init(w) {
  jscoverage_isInvertedMode = true;
  w._$jscoverage = w.parent._$jscoverage;
}

var jscoverage_currentFile = null;
''' + js[end:] + '''

function jscoverage_jsbloat_init() {
  // It is not obvious how to enable the source tab, so initialize the
  // js_coverage data structures (and alter the UI) as if the link had been
  // clicked.
  var anchor = document.querySelector('#summaryTbody a');
  var file = anchor.firstChild.nodeValue;
  jscoverage_currentFile = file;
  var tab = document.getElementById('sourceTab');
  tab.className = '';
  tab.onclick = jscoverage_tab_click;

  // Add a "Hide" button in the same place as the "Show" button.
  var h1 = document.querySelector('h1');
  h1.style.display = 'inline-block';
  h1.style.marginLeft = '200px';

  var hideButton = document.createElement('input');
  hideButton.type = 'button';
  hideButton.style.position = 'absolute';
  hideButton.style.top = '0';
  hideButton.style.left = '0';
  hideButton.value = 'Hide JSCoverage results';
  hideButton.addEventListener(
      'click',
      function(e) { parent.__JSBLOAT__.hide(); },
      false);
  document.body.appendChild(hideButton);
}
'''

# Modify the onload handler so it notifies the parent JS.
html = open('build/instrumented/jscoverage.html').read()
html = html.replace('onload="jscoverage_body_load();"',
    'onload="jscoverage_body_load(); parent.__JSBLOAT__.notifyLoaded()"')

# Inject the modified JS in place of the script tags.
html = html.replace('<script type="text/javascript" src="jscoverage.js"></script>',
    '<script>' + js + '</script>')

# Inject a base href so the image and CSS references work.
# TODO(bolinfest): Do not depend on external resources.
html = html.replace('href="jscoverage-highlight.css"',
    'href="http://siliconforks.com/jscoverage/instrumented/jscoverage-highlight.css"')
html = html.replace('href="jscoverage.css"',
    'href="http://siliconforks.com/jscoverage/instrumented/jscoverage.css"')
# Do this so images work correctly.
html = html.replace('<div id="mainDiv">',
    '<base href="http://siliconforks.com/jscoverage/instrumented/"><div id="mainDiv">')

# Escape characters as needed.
html = html.replace('\\', '\\\\')
html = html.replace('\r', '')
html = html.replace('\n', '\\n')
html = html.replace('"', '\\"')
html = html.replace('</script>', '<\\/script>')
jsc_var = 'var JS_COVERAGE_HTML = "%s";\n' % html

out = open('build/jsc_var.js', 'w')
out.write(jsc_var)
out.close()
